<template>
  <div class="upload-section">
    <h2>普通上传</h2>
    <el-upload
      ref="upload"
      :file-list="fileList"
      class="upload-demo"
      :on-change="handleSingleFileUpload"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :auto-upload="false"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      <el-button type="success" @click="submitUpload" :disabled="!singleFile"
        >上传</el-button
      >
    </el-upload>
    <h6>用户文件信息</h6>
    <el-table :data="userFiles" style="width: 75%">
      <el-table-column
        prop="file_name"
        label="文件名"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="file_size"
        label="文件大小"
        width="190"
      ></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="text" @click="downloadFile(scope.row.file_sha1, scope.row.file_name)"
            >下载</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <span class="demonstration">大于 7 页时的效果</span>
      <el-pagination
        layout="prev, pager, next"
        :total="totalPages"
        :current-page="currentPage"
        @current-change="handlePageChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import {
  simpleFileUploadApi,
  getFileListApi,
  downLoadFileApi,
} from "@/api/file.js"; // 从你的 API 文件中导入

export default {
  setup() {
    const fileList = ref([]);
    const singleFile = ref(null);
    const userFiles = ref([]);
    const filehash = ref(null);
    const userName = localStorage.getItem("customer") || "root";
    const currentPage = ref(1); // 当前页码
    const totalPages = ref(1);

    const handleSingleFileUpload = (file) => {
      singleFile.value = file.raw;
    };

    const beforeUpload = (file) => {
      const isLt1K = file.size / 1024 < 1; // 检查文件大小是否小于1KB

      if (!isLt1K) {
        ElMessage.error("图片大小不能超过1 KB!");
        return false; // 如果文件大小超过1KB，则阻止上传
      }
      // 可以在这里添加其他检查，例如文件类型检查
      return true; // 如果所有检查通过，则允许上传
    };

    const submitUpload = async () => {
      if (singleFile.value) {
        try {
          const response = await simpleFileUploadApi(
            userName,
            singleFile.value
          );

          if (response.status === 200) {
            ElMessage.success("文件上传成功");
            fileList.value = []; // 清空文件列表
            singleFile.value = null;
          } else {
            ElMessage.error("文件上传失败");
          }
        } catch (error) {
          console.error("上传失败:", error);
          ElMessage.error("文件上传失败");
        }
      } else {
        ElMessage.warning("请选择一个文件");
      }
    };

    const handleSuccess = (response, file) => {
      ElMessage.success("文件上传成功");
      // 这里可以处理成功后的逻辑
    };

    const handleError = (error, file) => {
      ElMessage.error("文件上传失败");
      console.error("上传失败:", error);
    };

    const preview = async (page = 1) => {
      try {
        const response = await getFileListApi(userName, page);
        if (response.data && Array.isArray(response.data.data)) {
          userFiles.value = response.data.data.map((item) => ({
            file_name: item.file_name,
            file_size: item.file_size,
            file_sha1: item.file_sha1,
          }));
          totalPages.value = Math.ceil(response.data.total);
        } else {
          ElMessage.error("返回的数据格式不正确");
          console.error("返回的数据格式不正确:", response.data);
        }
      } catch (error) {
        ElMessage.error("获取文件列表失败");
        console.error("获取文件列表失败:", error);
      }
    };

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
      preview(newPage);
    };

    const downloadFile = async (filehash, filename) => {
  console.log("下载文件的 hash:", filehash); // 调试信息
  console.log("下载文件的名称:", filename); // 调试信息
  try {
    const response = await downLoadFileApi(filehash);
    if (response && response.data && response.status === 200) {
      // 假设文件是JPEG图片，设置MIME类型为'image/jpeg'
      const blob = new Blob([response.data], {
        type: "application/octet-stream" // 设置正确的MIME类型
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      // 确保文件名包含正确的扩展名，例如 '.jpg'
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
      console.log("下载成功");
    } else {
      ElMessage.error("文件下载失败");
      console.error("请求失败:", response.data.error);
    }
  } catch (error) {
    ElMessage.error("下载文件失败");
    console.error("下载文件失败:", error);
  }
};

    onMounted(() => {
      preview();
    });

    return {
      fileList,
      singleFile,
      userFiles,
      handleSingleFileUpload,
      beforeUpload,
      submitUpload,
      handleSuccess,
      handleError,
      preview,
      downloadFile,
      currentPage,
      handlePageChange,
      totalPages,
    };
  },
};
</script>

<style scoped>
.upload-section {
  margin: 1rem;
}
</style>